package com.example.security;

import com.example.domain.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements UserDetails, Serializable {
 
 
    private Long id;
 
    private String username;

    private String password;

    private Integer role;

    private List<String> permissions;

    private List<SimpleGrantedAuthority> authorities;


    //两个参数的构造方法
    public LoginUser(User user, List<String> permissions) {
        this.id = user.getId();
        this.username = user.getUsername();
        this.password = user.getPassword();
        this.role = user.getRole();
        this.permissions = permissions;
    }

    public LoginUser(Long id, String username, Integer role, List<String> permissions, List<SimpleGrantedAuthority> authorities) {
        this.id = id;
        this.username = username;
        this.role = role;
        this.permissions = permissions;
        this.authorities = authorities;
    }


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(authorities!=null){
            return authorities;
        }
        //把permissions中String类型的权限信息封装成SimpleGrantedAuthority对象
        authorities = new ArrayList<>();
        for (String permission : permissions) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + permission);
            authorities.add(authority);
        }
        return authorities;
    }


    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
 
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
 
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
 
    @Override
    public boolean isEnabled() {
        return true;
    }

    // 序列化
    private static final long serialVersionUID = 1L;
}